package com.auto.nastoolbox.screens

import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.ColumnScope
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.rememberScrollState
import androidx.compose.foundation.text.KeyboardOptions
import androidx.compose.foundation.verticalScroll
import androidx.compose.material.icons.Icons
import androidx.compose.material.icons.filled.AccountBox
import androidx.compose.material.icons.filled.Delete
import androidx.compose.material.icons.filled.Home
import androidx.compose.material.icons.filled.Info
import androidx.compose.material3.AlertDialog
import androidx.compose.material3.Button
import androidx.compose.material3.Card
import androidx.compose.material3.CardDefaults
import androidx.compose.material3.Icon
import androidx.compose.material3.MaterialTheme
import androidx.compose.material3.OutlinedTextField
import androidx.compose.material3.Switch
import androidx.compose.material3.Text
import androidx.compose.material3.TextButton
import androidx.compose.runtime.Composable
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.saveable.rememberSaveable
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.graphics.vector.ImageVector
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.text.input.KeyboardType
import androidx.compose.ui.text.input.PasswordVisualTransformation
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.hilt.navigation.compose.hiltViewModel
import androidx.navigation.NavHostController
import com.auto.base.ui.HandleUiEvent
import kotlinx.coroutines.launch

/**
 * Created by YuanWei1 on 2025/6/5.
 *
 * Description:
 */
@Composable
fun SettingScreen(navController: NavHostController) {
    val viewModel: SettingViewModel = hiltViewModel()
    HandleUiEvent(viewModel, navController)
    var mIp by remember { mutableStateOf("点击设置Ip") }
    var showIpDialog by rememberSaveable { mutableStateOf(false) }
    var showLoginDilaog by rememberSaveable { mutableStateOf(false) }
    if (showIpDialog) {
        IpInputDialog(viewModel, mIp, onDismiss = {
            showIpDialog = false
        })
    }
    if (showLoginDilaog) {
        LoginDialog(onDismiss = {
            showLoginDilaog = false
        })
    }
    Column(modifier = Modifier.verticalScroll(rememberScrollState())) {
        Text(text = "设置", style = MaterialTheme.typography.headlineMedium, modifier = Modifier.padding(16.dp))
        // 分组1：显示设置
        SettingsCategory(title = "Nas设置") {
            SimpleSetting(title = mIp, icon = Icons.Default.AccountBox) {
                showIpDialog = true
            }
        }
        SettingsCategory("青龙面板") {
            SimpleSetting(title = "点击登录", icon = Icons.Default.Home) {
                showLoginDilaog = true
            }
        }
        // 操作项
        SettingsCategory {
            SimpleSetting(title = "清除缓存", icon = Icons.Default.Delete)
            SimpleSetting(title = "关于应用", icon = Icons.Default.Info)
        }
    }
}

@Composable
fun LoginDialog(
    onDismiss: () -> Unit = {},
    onLogin: (String, String) -> Unit = { name, pwd -> }
) {
    var username by remember { mutableStateOf("") }
    var password by remember { mutableStateOf("") }

    AlertDialog(
        onDismissRequest = onDismiss,
        title = { Text("青龙面板") },
        text = {
            Column {
                OutlinedTextField(
                    value = username,
                    onValueChange = { username = it },
                    label = { Text("用户名") },
                    modifier = Modifier.fillMaxWidth()
                )
                Spacer(modifier = Modifier.height(16.dp))
                OutlinedTextField(
                    value = password,
                    onValueChange = { password = it },
                    label = { Text("密码") },
                    visualTransformation = PasswordVisualTransformation(),
                    modifier = Modifier.fillMaxWidth()
                )
            }
        },
        confirmButton = {
            Button(
                onClick = { onLogin(username, password) },
                enabled = username.isNotBlank() && password.isNotBlank()
            ) {
                Text("登录")
            }
        },
        dismissButton = {
            TextButton(onClick = onDismiss) {
                Text("取消")
            }
        }
    )
}

//模块card
@Composable
fun SettingsCategory(
    title: String? = null, content: @Composable ColumnScope.() -> Unit
) {
    Column(modifier = Modifier.padding(vertical = 8.dp)) {
        title?.let {
            Text(text = it, style = MaterialTheme.typography.labelMedium, color = MaterialTheme.colorScheme.primary, modifier = Modifier.padding(start = 16.dp, top = 8.dp, bottom = 8.dp))
        }
        Card(modifier = Modifier.fillMaxWidth(), colors = CardDefaults.cardColors(containerColor = MaterialTheme.colorScheme.surface)) {
            Column(content = content)
        }
    }
}

//带开关的条目
@Composable
fun SwitchSetting(
    title: String, checked: Boolean, onCheckedChange: (Boolean) -> Unit
) {
    Row(modifier = Modifier
        .fillMaxWidth()
        .clickable { onCheckedChange(!checked) }
        .padding(16.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.SpaceBetween) {
        Text(text = title, style = MaterialTheme.typography.bodyLarge)
        Switch(checked = checked, onCheckedChange = onCheckedChange)
    }
}

/**
 * Simple setting
 *  文本标签的条目
 */
@Composable
fun SimpleSetting(
    title: String, icon: ImageVector, onClick: () -> Unit = {}
) {
    Row(modifier = Modifier
        .fillMaxWidth()
        .clickable { onClick() }
        .padding(16.dp), verticalAlignment = Alignment.CenterVertically) {
        Icon(imageVector = icon, contentDescription = null)
        Spacer(modifier = Modifier.width(16.dp))
        Text(text = title, style = MaterialTheme.typography.bodyLarge)
    }
}

@Composable
fun IpInputDialog(
    viewModel: SettingViewModel,
    ip: String = "", onDismiss: () -> Unit = {}, onConfirm: (String) -> Unit = {}
) {
    var ipAddress by remember { mutableStateOf(ip ?: "") }
    var isError by remember { mutableStateOf(false) }
    val context = LocalContext.current
    val scope = rememberCoroutineScope()
    AlertDialog(onDismissRequest = onDismiss, title = { Text("输入IP地址") }, text = {
        Column {
            OutlinedTextField(value = ipAddress, onValueChange = {
                ipAddress = it
                isError = false
            }, label = { Text("IP地址") }, isError = isError, keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number), modifier = Modifier.fillMaxWidth())
            if (isError) {
                Text(text = "请输入有效的IP地址", color = MaterialTheme.colorScheme.error, style = MaterialTheme.typography.labelSmall, modifier = Modifier.padding(top = 4.dp))
            }
        }
    }, confirmButton = {
        Button(onClick = {
            if (isValidIp(ipAddress)) {
                scope.launch {
                    viewModel.saveIp(ipAddress)
                }
                onConfirm(ipAddress)
                onDismiss()
            } else {
                isError = true
            }
        }) {
            Text("确认")
        }
    }, dismissButton = {
        Button(onClick = onDismiss) {
            Text("取消")
        }
    })
}

private fun isValidIp(ip: String): Boolean {
    val pattern = Regex("^((25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$")
    return pattern.matches(ip)
}
